#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

typedef struct 
{
	int id;
	char name[30];
	double salary;
}employee ;

int search_id(const char *filename , int id)
{
	int fd = open(filename,O_RDONLY,666);
	employee emp ;
	int size = read(fd,&emp,sizeof(emp)) ;
	while(size)
	{
		if(id == emp.id)
			return 1;
		size = read(fd,&emp,sizeof(emp)) ;
	}	
	return 0;
	close(fd);
}

void writeemp(const char * filename)
{
	int fd = open(filename , O_CREAT | O_RDWR | O_APPEND , 0666);
	char name[30] = {};
	if(fd == -1) 
	{
		perror("open");
		exit(-1);
	}
	employee emp ;
	while(1)
	{
		printf("请输入用户ID：");
		scanf("%d",&emp.id);
		scanf( "%*[^\n]");
	    scanf("%*c");
	    if(!search_id(filename , emp.id))
	    {
	       	printf( "请输入用户姓名 : " );
	        fgets(name, sizeof(name), stdin);
	        if (strlen(name) == sizeof (name) - 1 && name[sizeof(name) - 2] != '\n')
	        {
	          	scanf( "%*[^\n]");
	            scanf( "%*c");
	        }
	        strcpy(emp.name , name);
	        printf("请输入用户薪资：");
			scanf("%lf",&emp.salary);
			scanf( "%*[^\n]");
		    scanf("%*c");	        
		    write(fd,&emp,sizeof(emp));
		        
		    printf("是否还需继续输入？Y or N ");
		    char c ;
		    scanf("%c",&c);
		    if(c == 'N' || c == 'n')
		      	break;
		}
	    else
	    {
	       	printf( "此用户ID已存在，请重新输入.\n" );
		}
	        
	}	
	close(fd);
}

void reademp(const char * filename)
{
	int fd = open(filename,O_RDWR);
	if(fd == -1) 
	{
		perror("open");
		exit(-1);
	}
	employee emp;
	int size = read(fd,&emp,sizeof(emp)) ;
	while(size)
	{
		printf("此用户的ID：%d\n",emp.id);
		printf("此用户的名称：%s\n",emp.name);
		printf("此用户的：%lf\n",emp.salary);
		size = read(fd,&emp,sizeof(emp)) ;
	}
	close(fd);
}

int main()
{
	writeemp("b.dat");
	reademp("b.dat");
}
